package com.feature.learn.concurrent.Semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Description
 * @create 2021/6/30
 * @since 1.0.0
 */
public class SemaphoreSample1 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        Semaphore semp = new Semaphore(5);

        for (int i = 0; i < 20; i++) {
            int index = i;
            executorService.execute(() -> {
                try {
                    // 获得许可才能执行
                    semp.acquire();
                    System.out.println("accessing: " + index);
                    //模拟实际业务逻辑
                    Thread.sleep((long) (Math.random() * 1000));
                    // 访问完后，释放
                    semp.release();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 退出线程池
        executorService.shutdown();
    }
}